<script setup>
import { computed, onMounted, reactive, ref } from 'vue';
// 引入插件
import VuePdfEmbed from 'vue-pdf-embed';
import * as pdfjsLib from 'pdfjs-dist';

const props = defineProps({
  url: {
    type: String,
    required: true
  },
  useIframe: {
    type: Boolean,
    default: false
  }
});

const pdf = ref(null);

// 定义
const state = reactive({
  source: '', // pdf文件地址
  pageNum: 0, // 当前页面
  scale: 1, // 缩放比例
  numPages: 0 // 总页数
});
const scale = computed(() => `transform:scale(${state.scale})`);

onMounted(() => {
  // 首先请求接口，获取pdf存放地址，赋值给pdfUrl（此处省略请求代码）
  // 拿到pdf路径后，执行下面的函数
  getPdfUrl(props.url);
});
function getPdfUrl(data) {
  state.source = data;
  pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
  const loadingTask = pdfjsLib.getDocument(data);
  loadingTask.promise.then(pdf => {
    state.numPages = pdf.numPages;
  });
}
// 放大
function pageZoomOut() {
  if (state.scale < 2) {
    state.scale += 0.1;
  }
}
// 缩小
function pageZoomIn() {
  if (state.scale > 1) {
    state.scale -= 0.1;
  }
}

function print() {
  pdf.value.print();
}
</script>

<template>
  <div class="pdf-viewer h-full w-full">
    <template v-if="!useIframe">
      <div class="page-tool">
        <div class="page-tool-item" @click="pageZoomOut">放大</div>
        <div class="page-tool-item" @click="pageZoomIn">缩小</div>
        <div class="page-tool-item" @click="print">打印</div>
      </div>
      <VuePdfEmbed ref="pdf" :source="state.source" :style="scale" :page="state.pageNum" class="vue-pdf-embed" />
    </template>
    <template v-else>
      <iframe :src="url" class="pdf-iframe h-full w-full"></iframe>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.pdf-viewer {
  .vue-pdf-embed {
    width: 1000px;
    margin: 0 auto;
    border: 0 !important;
  }
}

.page-tool {
  display: flex;
  position: absolute;
  top: 5px;
  left: 50%;
  z-index: 100;
  transform: translateX(-50%);
  align-items: center;
  background: rgb(66 66 66);
  color: white;
  border-radius: 19px;
  cursor: pointer;
  justify-content: center;
  font-size: 15px;
}
.page-tool-item {
  padding: 4px 10px;
  cursor: pointer;
}
</style>
